package assignment;

import java.io.*;

public class Assignment2 {

	private String originalMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	private int getPosition(char c, char[] map) {
		c = Character.toUpperCase(c);
		int x = -1;
		for (int i = 0; i < map.length; i++) {
			if (c == map[i]) {
				x = i;
				break;
			}
		}

		return x;
	}

	private char[] getRotMap(char[] map, int rotation) {
		char[] rotMap = new char[map.length];
		if (rotation == 0)
			rotMap = map;
		else if (rotation < 0) {
			int index = 0;
			for (int i = map.length - Math.abs(rotation); i < map.length; i++) {
				rotMap[index] = map[i];
				index++;
			}
			for (int i = 0; i < map.length - Math.abs(rotation); i++) {
				rotMap[index] = map[i];
				index++;
			}
		} else {
			int index = 0;
			for (int i = rotation; i < map.length; i++) {
				rotMap[index] = map[i];
				index++;
			}
			for (int i = 0; i < rotation; i++) {
				rotMap[index] = map[i];
				index++;
			}
		}

		return rotMap;
	}

	public String encryt(String s, int rotation) {
		String rs = "";

		if (Math.abs(rotation) > 26)
			rotation = rotation % 26;

		char[] map = this.originalMap.toCharArray();
		char[] rotMap = getRotMap(map, rotation);

		for (char c : s.toCharArray()) {
			int pos = getPosition(c, map);
			if (pos == -1) {
				rs += c;
				continue;
			}

			if (Character.isLowerCase(c))
				rs += Character.toLowerCase(rotMap[pos]);
			if (Character.isUpperCase(c))
				rs += Character.toUpperCase(rotMap[pos]);
		}

		return rs;
	}

	public void encryptFile(String infile, String outfile, int rotation) throws IOException {
		File src = new File(infile);
		InputStreamReader isr = new InputStreamReader(new FileInputStream(src));
		BufferedReader reader = new BufferedReader(isr);
		String s = reader.readLine();		
		reader.close();
		isr.close();
		
		//... // Do the enryption here and get the encrypted string.
		
		// Write the encrypted string to 'outfile' what we learnt before.
		
	}

	public static void main(String[] args) {
		Assignment2 cc = new Assignment2();
		System.out.print(cc.encryt("Hellow World", 27));

	}

}
